Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

For-else Loop

for-else example

Examples of for-else loops with different data types in Python

Iterating over a list:

Iterating over list using for-else loop in python fruits = ["apple", "banana", "cherry"] for fruit in fruits: if fruit == "mango": print("Mango is in the list") break else: print("Mango is not in the list")

Output

Mango is not in the list

Iterating over a string:

Iterating over string using for-else loop in python for char in "Hello": if char == "z": print("The string contains 'z'") break else: print("The string does not contain 'z'")

Output

The string does not contain 'z'

Iterating over a dictionary:

Iterating dictionary type using for-else loop in python person = {"name": "Alice", "age": 25} for key in person: if key == "address": print("The dictionary contains 'address'") break else: print("The dictionary does not contain 'address'")

Output

The dictionary does not contain 'address'

Iterating over a set:

Iterating set datatype using for-else loop in python unique_numbers = {1, 2, 3, 2, 1} for num in unique_numbers: if num == 0: print("The set contains 0") break else: print("The set does not contain 0")

Output

The set does not contain 0

Iterating over a tuple:

Iterating tuple using for-else loop in python coordinates = (1, 2, 3) for coordinate in coordinates: if coordinate == 0: print("The tuple contains 0") break else: print("The tuple does not contain 0")

Output

The tuple does not contain 0

In each of these examples, the for loop goes through each item in the iterable (list, string, dictionary, set, or tuple) and executes the code block for each item. If the for loop completes normally (without encountering a break), the else block is executed.

  📌TAGS

★python ★ loop ★ for-else

Tutorials